package com.zx.scp.filter;

import com.zx.platform.utils.PmpUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务中心白名单策略 访问控制
 *
 * @author jefferry.lu
 */
public class SecurityCenterFilter extends HttpServlet implements Filter {

    private static Map<String, String> agreeIpList = new HashMap<String, String>();

    static {
        agreeIpList.put("115.29.111.51", "115.29.111.51");
        agreeIpList.put("10.163.219.188", "10.163.219.188");
    }

    /**
     * log
     */
    private static Logger log = Logger.getLogger(SecurityCenterFilter.class);

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String ip = PmpUtils.getIpAddr(req);
        String uri = req.getRequestURI();
        //对外部通知返回取现拦截  扫码 无卡 出款
        if (uri.contains("/nocard/callback")
                || uri.contains("/nocard/notifyOrder")
                || uri.contains("/yintong/notifyPay")) {
            filterChain.doFilter(request, response);
            return;
        }
        if (!agreeIpList.containsKey(ip))//如果非内部访问 进行拦截
        {
            log.info("非法访问ip addr:" + ip);
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendRedirect(req.getContextPath()
                    + "/index.jsp");
            return;
        }
        filterChain.doFilter(request, response);
        return;
    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
